package com.hong.spring.netty;

import com.alibaba.fastjson.JSONObject;
import com.hong.spring.dao.UserMapper;
import com.hong.spring.entity.User;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;

/**
 * @author: csh
 * @Date: 2021/1/19 11:08
 * @Description:websocket监听
 */
@Component
@ChannelHandler.Sharable
public class NettyWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    private SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Autowired
    private UserMapper userMapper;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("");
        //1.获取Channel通道
        final Channel channel=ctx.channel();
        channel.writeAndFlush(new TextWebSocketFrame("收到啦"));
        channel.writeAndFlush("收到啦");
    }

    //接受浏览器消息
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        System.out.println("收到消息 " + msg.text());
        if(msg.text().startsWith("com.hong.spring.service.IUserService.findById")){
            String[] list = msg.text().split("#");
            if(null==list || list.length<=0){
                ctx.writeAndFlush(new TextWebSocketFrame("没有id"));
            }
            User user = userMapper.findById(Integer.parseInt(list[1]));
            ctx.writeAndFlush(new TextWebSocketFrame(JSONObject.toJSONString(user)));
        }else{
            ctx.writeAndFlush(new TextWebSocketFrame("没有收到值啊！"));
        }
    }

    //当web客户端连接后，触发方法
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        System.out.println("用户连接:"+ctx.channel().id());
    }

    //当web客户端断开后，触发方法
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("用户断开:"+ctx.channel().id());
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        System.out.println(ctx.channel().id()+"促发事件");
        super.userEventTriggered(ctx, evt);
    }
}
